/**
 * 应用入口文件
 * 职责：Vue应用初始化、插件注册、全局配置
 */
import { createApp } from "vue"
import App from "./App.vue"
import router from "./router"
import { createPinia } from "pinia"
import piniaPluginPersistedstate from "pinia-plugin-persistedstate"
import ElementPlus from "element-plus"
import "element-plus/dist/index.css"

// 样式导入
import "@/styles/index.scss"
import "md-editor-v3/lib/preview.css"

// 工具导入
import { initIconSystem } from "@/utils/ui/icons"
import { config } from "md-editor-v3"
import { secureMarkdownConfig } from "@/utils/security/markdown"
import { setupErrorHandler, setupNetworkMonitor, setupPerformanceMonitor } from "@/utils/core/error-handler"
import { logger } from "@/utils/core/logger"
import { initTheme } from "@/composables/ui/useTheme"
import { secureStorage } from "@/utils/core/storage"

// 全局配置
config(secureMarkdownConfig);

// 自定义指令
const autoScrollDirective = {
  updated(el, binding) {
    if (binding.arg === "bottom" && el.lastElementChild) {
      setTimeout(() => {
        el.lastElementChild.scrollIntoView({ behavior: "smooth" });
      }, 50);
    }
  },
};

// 创建应用实例
const app = createApp(App);
const pinia = createPinia();

// 配置 Pinia
pinia.use(piniaPluginPersistedstate);

// 注册插件
app.use(pinia);
app.use(router);
app.use(ElementPlus);
app.directive("auto-scroll", autoScrollDirective);

// 设置全局错误处理
setupErrorHandler(app);

// 初始化监控系统
const isPerformanceMonitorEnabled = import.meta.env.VITE_PERFORMANCE_MONITOR === 'true';
if (isPerformanceMonitorEnabled) {
  setupNetworkMonitor();
  setupPerformanceMonitor();
}

// 初始化主题和存储
initTheme();
secureStorage.cleanExpired();

// 应用初始化
async function initApp() {
  try {
    await initIconSystem(app, {
      preloadCore: true,
      registerAll: false,
    });

    app.mount("#app");

    if (import.meta.env.DEV) {
      logger.info("应用初始化完成");
    }
  } catch (error) {
    if (import.meta.env.DEV) {
      logger.error("应用初始化失败:", error);
    }
    app.mount("#app");
  }
}

initApp();
